<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户登录</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .login-container {
            background: white;
            border-radius: 16px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.3);
            padding: 40px;
            width: 100%;
            max-width: 400px;
        }

        .login-header {
            text-align: center;
            margin-bottom: 30px;
        }

        .login-header h1 {
            font-size: 28px;
            color: #333;
            margin-bottom: 10px;
        }

        .login-header p {
            color: #666;
            font-size: 14px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 500;
            font-size: 14px;
        }

        .form-group input {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s;
        }

        .form-group input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .btn {
            width: 100%;
            padding: 14px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s;
            margin-bottom: 15px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        .btn-secondary {
            background: white;
            color: #667eea;
            border: 2px solid #667eea;
        }

        .btn-secondary:hover {
            background: #f5f5f5;
        }

        .message {
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: none;
            font-size: 14px;
        }

        .message.success {
            background: #e8f5e9;
            color: #2e7d32;
            border: 1px solid #4caf50;
        }

        .message.error {
            background: #ffebee;
            color: #c62828;
            border: 1px solid #f44336;
        }

        .message.show {
            display: block;
        }

        .link {
            text-align: center;
            margin-top: 20px;
            color: #666;
            font-size: 14px;
        }

        .link a {
            color: #667eea;
            text-decoration: none;
            font-weight: 500;
        }

        .link a:hover {
            text-decoration: underline;
        }

        .captcha-group {
            display: flex;
            gap: 10px;
            align-items: flex-end;
        }

        .captcha-input {
            flex: 1;
        }

        .captcha-image {
            width: 120px;
            height: 40px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
            background: #f5f5f5;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #999;
            font-size: 12px;
        }

        .captcha-image img {
            width: 100%;
            height: 100%;
            border-radius: 6px;
        }

        .captcha-image:hover {
            border-color: #667eea;
            transform: scale(1.05);
        }

        .loading {
            opacity: 0.6;
            pointer-events: none;
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="login-header">
            <h1>🔐 用户登录</h1>
            <p>欢迎回来，请登录您的账号</p>
        </div>

        <div class="message" id="message"></div>

        <form id="loginForm">
            <div class="form-group">
                <label>用户名</label>
                <input type="text" id="username" name="username" placeholder="请输入用户名" required autofocus>
            </div>

            <div class="form-group">
                <label>密码</label>
                <input type="password" id="password" name="password" placeholder="请输入密码" required>
            </div>

            <div class="form-group">
                <label>验证码</label>
                <div class="captcha-group">
                    <div class="captcha-input">
                        <input type="text" id="captchaCode" name="captchaCode" placeholder="请输入验证码" maxlength="4" required autocomplete="off">
                    </div>
                    <div class="captcha-image" id="captchaImage" onclick="refreshCaptcha()" title="点击刷新验证码">
                        加载中...
                    </div>
                </div>
            </div>

            <button type="submit" class="btn btn-primary">登录</button>
            <button type="button" class="btn btn-secondary" onclick="window.location.href='register.html'">注册账号</button>
        </form>

        <div class="link">
            没有账号？<a href="register.html">立即注册</a>
        </div>
    </div>

    <script>
        const API_BASE_URL = '/api/user';
        const CAPTCHA_API_URL = '/api/captcha';
        let currentCaptchaId = null;

        // 页面加载时获取验证码
        window.addEventListener('DOMContentLoaded', async () => {
            await refreshCaptcha();
            
            // 检查是否已登录
            const token = localStorage.getItem('token');
            if (token) {
                try {
                    const response = await fetch(`${API_BASE_URL}/validate`, {
                        headers: {
                            'Authorization': 'Bearer ' + token
                        }
                    });
                    const result = await response.json();
                    
                    if (result.code === 200) {
                        window.location.href = 'home.html';
                    }
                } catch (error) {
                    localStorage.clear();
                }
            }
        });

        // 刷新验证码
        async function refreshCaptcha() {
            const captchaImageEl = document.getElementById('captchaImage');
            captchaImageEl.classList.add('loading');
            captchaImageEl.innerHTML = '加载中...';
            
            try {
                const response = await fetch(`${CAPTCHA_API_URL}/generate`);
                const result = await response.json();
                
                if (result.code === 200) {
                    currentCaptchaId = result.data.captchaId;
                    captchaImageEl.innerHTML = `<img src="${result.data.captchaImage}" alt="验证码">`;
                    captchaImageEl.classList.remove('loading');
                    
                    // 清空验证码输入框
                    document.getElementById('captchaCode').value = '';
                } else {
                    captchaImageEl.innerHTML = '加载失败';
                    showMessage('❌ 验证码加载失败', 'error');
                }
            } catch (error) {
                console.error('获取验证码失败:', error);
                captchaImageEl.innerHTML = '加载失败';
                showMessage('❌ 验证码加载失败：' + error.message, 'error');
            }
        }

        document.getElementById('loginForm').addEventListener('submit', async (e) => {
            e.preventDefault();

            const formData = {
                username: document.getElementById('username').value.trim(),
                password: document.getElementById('password').value,
                captchaId: currentCaptchaId,
                captchaCode: document.getElementById('captchaCode').value.trim()
            };

            // 验证验证码输入
            if (!formData.captchaCode) {
                showMessage('❌ 请输入验证码', 'error');
                return;
            }

            try {
                const response = await fetch(`${API_BASE_URL}/login`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(formData)
                });

                const result = await response.json();

                if (result.code === 200) {
                    // 保存token到localStorage
                    localStorage.setItem('token', result.data.token);
                    localStorage.setItem('username', result.data.username);
                    localStorage.setItem('userId', result.data.userId);
                    localStorage.setItem('administrator', result.data.administrator);
                    localStorage.setItem('userLevel', result.data.userLevel || result.data.administrator || 0);

                    showMessage('✅ 登录成功！正在跳转...', 'success');
                    
                    setTimeout(() => {
                        window.location.href = 'home.html';
                    }, 1000);
                } else {
                    showMessage('❌ ' + result.message, 'error');
                    // 登录失败后刷新验证码
                    await refreshCaptcha();
                }

            } catch (error) {
                console.error('登录失败:', error);
                showMessage('❌ 登录失败：' + error.message, 'error');
                // 登录失败后刷新验证码
                await refreshCaptcha();
            }
        });

        function showMessage(text, type) {
            const messageEl = document.getElementById('message');
            messageEl.textContent = text;
            messageEl.className = `message ${type} show`;

            if (type === 'error') {
                setTimeout(() => {
                    messageEl.classList.remove('show');
                }, 5000);
            }
        }
    </script>
</body>
</html>

